package com.zf.shuashua.ui.mine;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Environment;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.aliyun.common.global.AliyunTag;
import com.aliyun.svideo.base.utils.Eyes;
import com.aliyun.svideo.base.utils.UploadConstant;
import com.aliyun.svideo.common.utils.FastClickUtil;
import com.aliyun.svideo.sdk.external.struct.common.VideoDisplayMode;
import com.aliyun.svideo.sdk.external.thumbnail.AliyunIThumbnailFetcher;
import com.aliyun.svideo.sdk.external.thumbnail.AliyunThumbnailFetcherFactory;
import com.bumptech.glide.Glide;
import com.meis.base.mei.base.BaseActivity;
import com.zf.shuashua.R;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class PublishVideoActivity extends BaseActivity {

    public static final String VIDEO_PATH = "video_path";
    public static final String VIDEO_WIDTH = "video_width";
    public static final String VIDEO_HEIGHT = "video_height";

    /**
     * 封面保存路径
     */
    // private final String PATH_THUMBNAIL = Environment.getExternalStorageDirectory() + File.separator + "thumbnail.jpg";

    private String videoPath = "";
    private int videoWidth;
    private int videoHeight;
    private String thumbPath;

    private ImageView ivCover;
    private EditText etDesc;

    private AliyunIThumbnailFetcher aliyunIThumbnailFetcher;

    private static final String ACTIVITY_ACTION_MAIN = "com.zf.shuashua.MainActivity";

    @Override
    protected void initView() {
        Eyes.setStatusBarColor(this, Color.parseColor("#111111"));

        findViewById(R.id.iv_back).setOnClickListener(v -> finish());

        ivCover = findViewById(R.id.publish_cover_blur);
        etDesc = findViewById(R.id.publish_desc);

        if (getIntent() != null) {
            videoPath = getIntent().getStringExtra(VIDEO_PATH);
            videoWidth = getIntent().getIntExtra(VIDEO_WIDTH, 0);
            videoHeight = getIntent().getIntExtra(VIDEO_HEIGHT, 0);
        }

        if (!TextUtils.isEmpty(videoPath)) {
            aliyunIThumbnailFetcher = AliyunThumbnailFetcherFactory.createThumbnailFetcher();
            aliyunIThumbnailFetcher.addVideoSource(videoPath);
            aliyunIThumbnailFetcher.setParameters(videoWidth, videoHeight,
                    AliyunIThumbnailFetcher.CropMode.Mediate, VideoDisplayMode.SCALE, 8);
            aliyunIThumbnailFetcher.requestThumbnailImage(new long[]{0}, new AliyunIThumbnailFetcher.OnThumbnailCompletion() {

                @Override
                public void onThumbnailReady(Bitmap bitmap, long l) {
                    thumbPath = Environment.getExternalStorageDirectory() + File.separator + System.currentTimeMillis() + ".jpg";
                    FileOutputStream fileOutputStream = null;
                    try {
                        fileOutputStream = new FileOutputStream(thumbPath);
                        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream);
                    } catch (IOException e) {
                        e.printStackTrace();
                    } finally {
                        if (fileOutputStream != null) {
                            try {
                                fileOutputStream.flush();
                                fileOutputStream.close();
                                fileOutputStream = null;
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }

                    Glide.with(mContext)
                            .load(thumbPath)
                            .into(ivCover);

                    // fetcher.release();
                }

                @Override
                public void onError(int errorCode) {
                    // fetcher.release();
                }
            });
        }

        ivCover.setOnClickListener(v -> {
            if (TextUtils.isEmpty(videoPath)) return;
            if (FastClickUtil.isFastClick()) {
                return;
            }
            Intent intent = new Intent(this, CoverEditActivity.class);
            intent.putExtra(CoverEditActivity.KEY_PARAM_VIDEO, videoPath);
            startActivityForResult(intent, 0);
        });

        etDesc.addTextChangedListener(new TextWatcher() {

            private int start;
            private int end;

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                start = etDesc.getSelectionStart();
                end = etDesc.getSelectionEnd();

                int count = count(s.toString());
                // 限定EditText只能输入10个数字
                if (count > 20 && start > 0) {
                    Log.d(AliyunTag.TAG, "超过10个以后的数字");

                    s.delete(start - 1, end);
                    etDesc.setText(s);
                    etDesc.setSelection(s.length());
                }
            }
        });

        findViewById(R.id.tv_preview).setOnClickListener(v -> {
            if (FastClickUtil.isFastClick()) {
                return;
            }
            Intent intent = new Intent(this, VideoPreviewActivity.class);
            intent.putExtra(VideoPreviewActivity.KEY_PATH_VIDEO, videoPath);
            startActivity(intent);
        });

        findViewById(R.id.tv_publish_video).setOnClickListener(v -> {
            if (FastClickUtil.isFastClick()) {
                return;
            }
            String desc = etDesc.getText().toString();
            if (TextUtils.isEmpty(desc)) {
                Toast.makeText(this, "请填写视频描述", Toast.LENGTH_SHORT).show();
                return;
            }

            try {
                Intent intent = new Intent();
                intent.setClassName(this, ACTIVITY_ACTION_MAIN);
                // intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

                intent.putExtra(UploadConstant.KEY_UPLOAD_VIDEO, videoPath);
                intent.putExtra(UploadConstant.KEY_UPLOAD_THUMBNAIL, thumbPath);
                intent.putExtra(UploadConstant.KEY_PARAM_VIDEO_RATIO, 0f);
                intent.putExtra(UploadConstant.KEY_UPLOAD_DESC, desc);
                intent.putExtra(UploadConstant.KEY_PARAM_IS_RECORD_VIDEO, false);

                startActivity(intent);
                finish();
            } catch (Exception e) {
            }
        });
    }

    private int count(String text) {
        int len = text.length();
        int skip;
        int letter = 0;
        int chinese = 0;
        for (int i = 0; i < len; i += skip) {
            int code = text.codePointAt(i);
            skip = Character.charCount(code);
            if (code == 10) {
                continue;
            }
            String s = text.substring(i, i + skip);
            if (isChinese(s)) {
                chinese++;
            } else {
                letter++;
            }

        }
        letter = letter % 2 == 0 ? letter / 2 : (letter / 2 + 1);
        int result = chinese + letter;
        return result;
    }

    // 完整的判断中文汉字和符号
    private boolean isChinese(String strName) {
        char[] ch = strName.toCharArray();
        for (int i = 0; i < ch.length; i++) {
            char c = ch[i];
            if (isChinese(c)) {
                return true;
            }
        }
        return false;
    }

    private boolean isChinese(char c) {
        Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
        if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
                || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_B
                || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION
                || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS
                || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION) {
            return true;
        }
        return false;
    }

    @Override
    protected void initData() {

    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_publish_video;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (aliyunIThumbnailFetcher != null) {
            aliyunIThumbnailFetcher.release();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 0 && resultCode == RESULT_OK) {
            thumbPath = data.getStringExtra(CoverEditActivity.KEY_PARAM_RESULT);
            Glide.with(mContext).load(thumbPath).into(ivCover);
        }
    }
}
